package org.example.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {
    // 数据库连接信息
    private static final String URL = "jdbc:mysql://localhost:3306/tll1?useSSL=false&serverTimezone=UTC";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";  // 根据你的实际密码修改

    // 单例实例
    private static DatabaseConnection instance;
    private Connection connection;

    // 私有构造函数
    private DatabaseConnection() {
        try {
            // 加载MySQL驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("MySQL驱动加载失败！");
            e.printStackTrace();
        }
    }

    // 获取实例的静态方法
    public static DatabaseConnection getInstance() {
        if (instance == null) {
            instance = new DatabaseConnection();
        }
        return instance;
    }

    // 获取数据库连接
    public Connection getConnection() throws SQLException {
        if (connection == null || connection.isClosed()) {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        }
        return connection;
    }

    // 关闭连接
    public void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                System.out.println("关闭数据库连接失败！");
                e.printStackTrace();
            }
        }
    }

    // 测试连接方法
    public boolean testConnection() {
        try {
            getConnection();
            System.out.println("数据库连接成功！");
            return true;
        } catch (SQLException e) {
            System.out.println("数据库连接失败！");
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) {
        // 获取数据库连接实例
        DatabaseConnection dbConnection = DatabaseConnection.getInstance();

// 测试连接
        dbConnection.testConnection();

        try {
            // 获取连接
            Connection conn = dbConnection.getConnection();

            // 使用连接执行SQL操作
            // ...
            System.out.println("连接成功");
            // 完成后关闭连接
            dbConnection.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
} 